//
//  BrowserViewController.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/10/23.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

class BrowserViewController: UIViewController {
    /// 保存当前选中的图片编号
    var indexpath: IndexPath
    /// 保存选中的图片数组
    var bmiddle_urls: [URL]
    
    init(bmiddle_urls: [URL], indexpath: IndexPath) {
        
        self.bmiddle_urls = bmiddle_urls
        self.indexpath = indexpath
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.red
        
        // 1.初始化所有UI
        setupUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 跳转到点击的图片上
        collectionView.scrollToItem(at: indexpath, at: UICollectionViewScrollPosition.left, animated: false)
    }
    
    //MARK:- 内部控制方法
    /// 初始化所有UI
    private func setupUI() {
        // 添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView" : collectionView])
        
        let views = ["closeButton" : closeButton, "saveButton" : saveButton]
        
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        var closeCons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[closeButton(100)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        closeCons += NSLayoutConstraint.constraints(withVisualFormat: "V:[closeButton(50)]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        var saveCons = NSLayoutConstraint.constraints(withVisualFormat: "H:[saveButton(100)]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        saveCons += NSLayoutConstraint.constraints(withVisualFormat: "V:[saveButton(50)]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
        
        // 添加约束
        view.addConstraints(cons)
        view.addConstraints(closeCons)
        view.addConstraints(saveCons)
        

    }
    
    
    /// 关闭按钮点击
    @objc private func closeButtonClick() {
        dismiss(animated: true, completion: nil)
    }
    
    /// 保存照片按钮点击
    @objc private func saveButtonClick() {
        ZHLog("saveClick")
    }
    
    //MARK:- 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        
        let clv = UICollectionView(frame: CGRect.zero, collectionViewLayout: ZHTQCollectionViewLayout())
        
        clv.backgroundColor = UIColor.gray
        clv.register(ZHTQCollectionViewCell.self, forCellWithReuseIdentifier: "browserCell")
        clv.dataSource = self
        clv.delegate = self
        return clv
    }()
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = {
       
        let btn = UIButton(type: UIButtonType.custom)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.setTitle("关闭", for: UIControlState.normal)
        btn.addTarget(self, action: #selector(closeButtonClick), for: UIControlEvents.touchUpInside)
        return btn
    }()
    
    /// 保存按钮
    private lazy var saveButton: UIButton = {
        
        let btn = UIButton(type: UIButtonType.custom)
        btn.backgroundColor = UIColor(white: 0.8, alpha: 0.5)
        btn.setTitle("保存", for: UIControlState.normal)
        btn.addTarget(self, action: #selector(saveButtonClick), for: UIControlEvents.touchUpInside)
        return btn
    }()
}

extension BrowserViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return bmiddle_urls.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "browserCell", for: indexPath) as! ZHTQCollectionViewCell
        
        cell.imageUrl = bmiddle_urls[indexPath.item]
        
        return cell
    }
}

/// 自定义cell的布局控件
class ZHTQCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepare() {
        
        itemSize = UIScreen.main.bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.horizontal
        
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}

/// 自定义cell控件
class ZHTQCollectionViewCell: UICollectionViewCell {
    
    var imageUrl: URL? {
        
        didSet{
            imageView.sd_setImage(with: imageUrl) { (image, error, _, _) in
                
                let width = UIScreen.main.bounds.width
                let height = UIScreen.main.bounds.height
                // 计算图片的宽高比
                let scale = (image?.size.height)! / (image?.size.width)!
                
                // 计算等比缩放的图片高度
                let imageHeight = width * scale
                
                // 给imageView复制尺寸
                self.imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: width, height: imageHeight))
                
                // 设置scrollView的内边距
                self.scrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                // 设置scrollView的内容范围
                self.scrollView.contentSize = CGSize(width: 0, height: 0)
                
                if imageHeight < height {
                    // 设置scrollView的内边距
                    let margen = (height - imageHeight) * 0.5
                    self.scrollView.contentInset = UIEdgeInsets(top: margen, left: 0, bottom: margen, right: 0)
                    // 设置scrollView的内容范围 滚动
                    self.scrollView.contentSize = CGSize(width: 0, height: 0)
                } else {
                    
                    // 设置scrollView的内容范围 滚动
                    self.scrollView.contentSize = CGSize(width: width, height: imageHeight)
                }
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 初始化UI控件
    private func setupUI() {
        // 添加子控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        // 布局子控件
        scrollView.frame = UIScreen.main.bounds
        scrollView.backgroundColor = UIColor.gray
        
        // 添加约束
    }
    
    //MARK:- 懒加载
    /// scrollView
    private lazy var scrollView = UIScrollView()
    
    /// 显示图片imageView
    private lazy var imageView = UIImageView()
}
